import { useEffect, useState } from 'react';
import { Form, Space, Col, Table, Input, Button, Tag, Popconfirm, Row, Select } from 'antd';
import { getManufacturerWithSchools, searchManufacturerWithSchools, updateManufacturer } from '../../api/manufacturer';
import type { ManufacturerWithSchools } from '../../types/manufacturer';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import ManufacturerModal from './modal';
import type { PopconfirmProps } from 'antd';
import { messageApi } from '../../utils/message';


const Manufacturer = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false)
    const [modelVisible, setModelVisible] = useState(false)
    const [temRecord, setTemRecord] = useState<ManufacturerWithSchools>()

    const [dataSource, setDataSource] = useState<ManufacturerWithSchools[]>([])


    const confirmPopconfirm: PopconfirmProps['onConfirm'] = (): void => {
        if (!temRecord) return
        const next = { ...temRecord, status: temRecord.status === 0 ? 1 : 0 }
        updateManufacturer(next).then(res => {

            messageApi.success('操作成功！')
            fetchData()
        })
    }

    const columns = [
        {
            title: '厂商名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '管理学校数量',
            dataIndex: 'schools',
            key: 'schools',
            render: (value: ManufacturerWithSchools['schools'], record: ManufacturerWithSchools) => {
                return record.schools.length
            }
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 120,
            render: (value: ManufacturerWithSchools['status']) => {
                return value === 0 ? <Tag color="red">禁用</Tag> : <Tag color="green">启用</Tag>
            }
        },
        {
            title: '操作',
            dataIndex: 'options',
            width: 120,
            render: (value: ManufacturerWithSchools['schools'], record: ManufacturerWithSchools) => {
                let color: "green" | "danger" = 'green';
                let text = '启用';
                if (record.status === 1) {
                    color = 'danger';
                    text = '禁用'
                }
                return <Popconfirm
                    key={record.id}
                    title={`要${text}厂商？`}
                    onConfirm={confirmPopconfirm}
                    okText="确定"
                    cancelText="取消"
                >
                    <Button color={color} variant="text" onClick={() => setTemRecord(record)}>
                        {text}
                    </Button>
                </Popconfirm>

            }
        }
    ];

    const fetchData = async () => {
        try {
            setLoading(true);
            // 并行请求数据
            const res = await getManufacturerWithSchools();
            setDataSource(res.manufacturers);
        } catch (error) {
            console.error('获取首页数据失败', error);
        } finally {
            setLoading(false);
        }
    };
    const handleReset = () => {
        form.resetFields()
        fetchData()
    }
    const renderForm = () => {
        return <Form
            form={form}
            initialValues={{}}
        >
            <Row>
                <Col span={8} >
                    <Form.Item label="厂商名称" name="name">
                        <Input placeholder="厂商名称" />
                    </Form.Item>
                </Col>
                <Col span={6} offset={1}>
                    <Form.Item label="状态" name='status'>
                        <Select
                            allowClear
                            options={[
                                { value: 0, label: '禁用' },
                                { value: 1, label: '启用' },
                            ]}
                        />
                    </Form.Item>
                </Col>
                <Col span={8} offset={1}>
                    <Space>
                        <Button icon={<SearchOutlined />} type="primary" onClick={handleSearch}>查询</Button>
                        <Button type="primary" onClick={handleReset}>重置</Button>
                    </Space>
                </Col>
            </Row>
            <Row>
                <Col span={24}>
                    <Form.Item>
                        <Button icon={<PlusOutlined />} type="primary" onClick={() => setModelVisible(true)}>新增</Button>

                    </Form.Item>
                </Col>
            </Row>

        </Form>
    }

    // 获取统计数据
    useEffect(() => {


        fetchData();
    }, []);

    const modalCallback = () => {
        fetchData();
        setModelVisible(false)

    }

    const handleSearch = async () => {
        const next = form.getFieldsValue(['name', 'status'])
        try {
            setLoading(true);
            const res = await searchManufacturerWithSchools(next);
            setDataSource(res.manufacturers);
        } catch (error) {
            console.error('获取数据失败', error);
        } finally {
            setLoading(false);
        }
    }



    return (
        <div>
            <div>
                {renderForm()}
            </div>
            <div >
                <Table loading={loading} dataSource={dataSource} columns={columns} />
            </div>
            <ManufacturerModal callback={modalCallback} visible={modelVisible} handleCancel={() => setModelVisible(false)}></ManufacturerModal>
        </div>
    );
};

export default Manufacturer;
